<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import CommonTree from './CommonTree.vue';
import type {
  TreeNode,
  TreeType,
  TreeTypeConfig,
  CustomerTreeProps,
} from './types';

const props = withDefaults(defineProps<CustomerTreeProps>(), {
  treeData: () => [],
  selectedKeys: () => [],
  checkedKeys: () => [],
  checkable: true,
  showIcon: true,
  checkStrictly: false,
  defaultType: '热源',
  treeList: () => ['热源', '热站', '小区', '热用户'],
});

const emit = defineEmits<{
  (e: 'update:selectedValue', value: TreeType): void;
  (e: 'update:nodeId', id: string | string[]): void;
  (e: 'update:level', level: number): void;
}>();

// 内部状态
const treeDataRef = ref<TreeNode[]>([]);
const selectedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);
const treeKey = ref(0); // 添加treeKey用于强制重新渲染树组件

// 选择相关的变量
const treeTypes = ref<TreeType[]>(props.treeList);
const currentType = ref<TreeType>(props.defaultType);

// 树类型配置
const treeTypeConfigs: Record<TreeType, TreeTypeConfig> = {
  热源: { type: '热源', apiType: 1, validLevel: 6 },
  热站: { type: '热站', apiType: 2, validLevel: 7 },
  小区: { type: '小区', apiType: 3, validLevel: 6 },
  热用户: { type: '热用户', apiType: 4, validLevel: 8 },
};

// 获取根节点数据
const fetchRootNodes = async (type: number) => {
  try {
    if (props.loadData) {
      const res = await props.loadData(type, '');
      const data = formatTreeData(res);
      treeDataRef.value = data;
    }
  } catch (error) {
    console.error('Failed to load root nodes:', error);
    message.error('加载根节点失败');
  }
};

// 初始化加载根节点
fetchRootNodes(treeTypeConfigs[currentType.value].apiType);

const formatTreeData = (data: any[]): TreeNode[] => {
  return data.map((item: any) => {
    const node: TreeNode = {
      key: item.id,
      id: item.id,
      level: item.level,
      title: item.title,
    };

    if (item.children && item.children.length > 0) {
      return {
        ...node,
        children: formatTreeData(item.children),
      };
    }

    return node;
  });
};

// 懒加载函数
const loadData = async (treeNode: any) => {
  if (treeNode.dataRef?.children || treeNode.dataRef?.isLeaf) {
    return;
  }

  try {
    if (props.loadData) {
      const res = await props.loadData(
        treeTypeConfigs[currentType.value].apiType,
        treeNode.id as string,
      );

      if (!res || res.length === 0) {
        message.warning('没有数据');
        return;
      }

      const children = formatTreeData(res);
      if (treeNode.dataRef) {
        treeNode.dataRef.children = children;
        treeNode.dataRef.isLeaf = children.length === 0;
      }
      treeDataRef.value = [...treeDataRef.value];
    }
  } catch (error) {
    console.error('Failed to load node data:', error);
    message.error('加载节点数据失败');
  }
};

const onSelect = (_selectedKeys: string[], info: any) => {
  const node = info.selectedNodes[0];
  if (!node) return;

  const config = treeTypeConfigs[currentType.value];
  const isValidSelection = node.level === config.validLevel;

  if (isValidSelection) {
    emit('update:nodeId', node.id);
  }
};

const onCheck = (_checkedKeys: string[], info: any) => {
  console.log(_checkedKeys,info)
  const value = info.checkedNodes.map((node: any) => node.key);
  const level = info.checkedNodes[0].level;
  console.log(level);
  emit('update:nodeId', value);
  emit('update:level', level);
};

// 监听类型变化
watch(currentType, (newValue) => {
  emit('update:selectedValue', newValue);

  // 重置树状态
  treeDataRef.value = [];
  selectedKeys.value = [];
  checkedKeys.value = [];
  treeKey.value += 1; // 增加key值，强制重新渲染树组件

  // 加载新类型的根节点
  fetchRootNodes(treeTypeConfigs[newValue].apiType);
});

// 初始化时触发一次
emit('update:selectedValue', currentType.value);
</script>

<template>
  <div class="customer-tree">
    <a-card :bordered="false" class="tree-card">
      <a-segmented v-model:value="currentType" :options="treeTypes" />
      <div class="tree-container">
        <CommonTree
          :key="treeKey"
          :tree-data="treeDataRef"
          v-model:selected-keys="selectedKeys"
          v-model:checked-keys="checkedKeys"
          :load-data="loadData"
          :checkable="checkable"
          :show-icon="showIcon"
          :check-strictly="checkStrictly"
          @select="onSelect"
          @check="onCheck"
        />
      </div>
    </a-card>
  </div>
</template>

<style lang="scss" scoped>
.customer-tree {
  .tree-card {
    width: 500px;
    height: 830px;
  }

  .tree-container {
    margin: 12px 0;
  }

  :deep(.ant-segmented-item-selected) {
    font-weight: bold;
    color: #006be6;
  }
}
</style>
